//提示
const tipMsg =(title,icon,time,mask)=>{
        title = title == undefined ? "系统繁忙" : title;
        icon = icon == undefined ? "none" : icon;
        time = time == undefined ? 1500 : time;
        mask = mask == undefined ? true : mask;
        uni.showToast({
            title:title,
            icon:icon,
            mask:mask,
            duration:time
        })
}
// 设置title
const setTitle = title =>{
	//如果需要在页面进入时设置标题，可以在onReady内执行，以避免被框架内的修改所覆盖
	//如果必须在onShow内执行需要延迟一小段时间
	uni.setNavigationBarTitle({
	    title: title
	})
}

//验证手机号
const checkPhone = phone=>{
    if(!(/^1[23456789]\d{9}$/.test(phone))){
        uni.showToast({
            title:"手机号格式不正确",
            icon:'none'
        })
        return false;
    }
    return true;
}

// 验证码邮箱
const checkEmail = email=>{
	if(!(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email))){
		uni.showToast({
		    title:"邮箱格式不正确",
		    icon:'none'
		})
		return false;
	}
	return true;
}

// 页面跳转
const jump = (url,clear)=>{
	//console.log(clear)
	clear ? 
	uni.reLaunch({
		url: url
	})
	:
	uni.navigateTo({
	    url: url
	})
}

const nowDate = ()=>{
	let date = new Date();
	let seperator1 = "-";
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	let currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate
}

const nowTime = ()=>{
	let date = new Date();
	let seperator1 = ":";
	let hours = date.getHours();
	let min = date.getMinutes();
	if (hours >= 0 && hours <= 9) {
		hours = "0" + hours;
	}
	if (min >= 0 && min <= 9) {
		min = "0" + min;
	}
	return hours + seperator1 + min
}

const back = (delta) =>{
	uni.navigateBack({
		delta:delta || 1
	})
}


const upload = (url,option = {})=>{
	return new Promise((resolve,reject)=>{
		uni.showLoading({
			title:'上传中...',
			mask:!0
		})
		uni.uploadFile({
			url:Vue.prototype.$u.http.config.baseUrl + url,
			name:option.name || 'file',
			filePath:option.filePath,
			formData:option.formData,
			header:option.header,
			success(res){
				uni.hideLoading()
				if(res.statusCode == 200){
					let data = JSON.parse(res.data)
					if(data.code == 1){
						resolve(data.data.value)
					}
				}else{
					reject(res)
				}
			},
			fail(err) {
				uni.hideLoading()
				reject(err)
			}
		})
	})
}

const getCode = ()=>{
	if (document.URL.match(/\?.*#/)) {
	    let temp = document.URL.match(/\?.*#/)[0]
	    if (temp.match(/=.*&/)) {
	      // 解析Code
	      let code = temp.match(/=.*&/)[0]
	      code = code.substr(1, code.length) // 去掉 ?
	      code = code.substr(0, code.length - 1)  // 去掉 #
	      // 重置URL(去掉code参数，避免重复调用)
	      window.history.pushState({}, 0, document.URL.replace(temp.substr(0, temp.length - 1), ''))
		  return code
	    }
		return false
	}
	return false
}

const getParams = (key)=>{
	const params = {}
	window.location.hash.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>params[k]=v)
	return key ? params[key] : params
}


const cookie = {
	set: function(name, value){
	  // 缓存过期时间
	  let Days = 30
	  let exp = new Date()
	  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
	  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
	},
	get: function(name){
	  let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
	  let reg = arr
	  arr = document.cookie.match(reg)
	  if (arr) {
	    return unescape(arr[2])
	  }else{
	    return null
	  }
	},
	del: function(name){
	  let exp = new Date()
	  exp.setTime(exp.getTime() - 1)
	  let cval = this.cookie.get(name)
	  if (cval != null) {
	    document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
	  }
	}
}

const h5Copy = (content)=>{
	if (!document.queryCommandSupported('copy')) {
		// 不支持
		return false
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	textarea.remove()
	return result
}

const agree = (text)=>{
	tipMsg(text || '请先阅读并同意协议')
}

const imgUrl = 'https://flw.soft.haoyangsoft.com'

// 全局混入
const mixin = {
	methods:{
		jump(url,type){
			this.$app.jump(url,type)
		},
		imgUrl(url){
			if(url === undefined) return imgUrl
			if(typeof url === 'string' && url.indexOf(',') >= 0){
				url = url.split(',')
			}
			if(Array.isArray(url) && url.length){
				url = url[0]
			}
			return	url.indexOf('http') === 0 ? url : imgUrl + url
		}
	}
}

const eventJump = (url)=>{
	if(url){
		let urlS = url.split(':')
		if(urlS.length == 1){
			// 普通跳转
			uni.navigateTo({
				url:url,
				fail() {
					uni.switchTab({
						url:url
					})
				}
			})
		}else if(urlS.length >= 2){
			// 带条件跳转
			/*
				/pages/index/index 普通跳转 支持普通页面tab页面
				tel:138000 拨号
				redirectTo:/pages/index/index 关闭当前页打开下一页
				webview:https://www.baidu.com 打开网页
				images:http://a.com/img.jpg,http://a.com/img.jpg 多图预览
				app:wxappid,pages/index/index 小程序跳转
				copy:文本内容 点击按钮复制内容
				toast:提示信息
			*/
			let type = ['tel','redirectTo','webview','images','app','copy','toast']
			let index = type.indexOf(urlS[0])
			if(index >= 0){
				switch (index)
				{
					case 0://拨号
					uni.makePhoneCall({
						phoneNumber:urlS[1]
					})
					break;//关闭当前页打开下一页
					case 1:
					uni.redirectTo({
						url:urlS[1]
					})
					break;
					case 2://webview
					urlS.shift()
					uni.navigateTo({
						url:'/pages/webview/webview?url=' + urlS.join(':')
					})
					break;
					case 3://查看图片
					urlS.shift()
					urlS = urlS.join(':')
					urlS = urlS.split(',')
					uni.previewImage({
						urls:urlS
					})
					break;
					case 4://跳转小程序
					urlS.shift()
					urlS = urlS.join(':')
					urlS = urlS.split(',')
					uni.navigateToMiniProgram({
						appId:urlS[0],
						path:urlS[1]
					})
					break;
					case 5://复制内容
					urlS.shift()
					urlS = urlS.join(':')
					uni.setClipboardData({
						data:String(urlS)
					})
					break;
					case 5://提示信息
					urlS.shift()
					urlS = urlS.join(':')
					tipMsg(urlS)
					break;
				}
			}
		}
	}
}

const showImg = (urls,current = 0)=>{
	uni.previewImage({
		urls,
		current
	})
}

const openXY = (id)=>jump(`/pages/news/contract?id=${id}`)

// 房源类型:1=新房,2=二手房,3=租房,4=商铺,5=地皮,6=厂房,7=独栋楼
// key 为文件夹路径
const TYPE_MAP = [{
	name:'新房',
	key:'newHouse'
},{
	name:'二手房',
	key:'oldHouse'
},{
	name:'租房',
	key:'renting'
},{
	name:'商铺',
	key:'shop'
},{
	name:'地皮',
	key:'land'
},{
	name:'厂房',
	key:'plant'
},{
	name:'独栋楼',
	key:'villa'
}]

module.exports = {
	tipMsg,
	checkPhone,
	checkEmail,
	jump,
	setTitle,
	nowDate,
	nowTime,
	back,
	imgUrl,
	upload,
	getCode,
	getParams,
	cookie,
	h5Copy,
	agree,//协议提示
	mixin,
	eventJump,
	showImg,
	TYPE_MAP,//房子类型
	openXY//打开合同
}